﻿package de.gameduell.framework.facebook.app.pyramide {
	import de.gameduell.framework.facebook.app.GameData;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;

	public class ForeignPyramidView extends PyramidView {
		
		public function ForeignPyramidView(aTimeline:Sprite, aPyramid:Pyramid) {
			super(aTimeline);
			stateLayer.visible = false;
			
			controller.gameData.removeEventListener(GameData.APP_INIT_DONE, onSetupDone);
			_pyramid.removeEventListener(Pyramid.NEW_CONSTRUCTION, updateLayout);
			_pyramid.removeEventListener(Pyramid.OUT_OF_BRICKS, onOutOfBricks);			
			_pyramid = aPyramid;
			
			onSetupDone();
		}
		
		
//		override protected function onSetupDone(event:Event = null):void {
//			if(_pyramid != null) {
//				for each(var aBrick:Brick in _pyramid.bricks) {
//					var aView:ForeignBrickView = new ForeignBrickView(aBrick, stateLayer, _pyramid.isForeign);
//					brickViews[aBrick.id] = aView;
//					pyrContainer.addChild(aView.sprite);
//					var xPos:int = int(aBrick.position.y) * (91) + (int(aBrick.position.x) * (90 / 2));
//					var yPos:int = int(aBrick.position.x) * -61;
//					aView.position = new Point(xPos, yPos);
//				}
//			}
//			updateLayout();
//			
//			if(_pyramid.currentBrick.id == "28") {
//				onOutOfBricks();
//			}
//		}
		
		override protected function onOutOfBricks(event:Event = null):void {
			topBrickView = ForeignBrickView(brickViews["28"]);
//			if(topBrickView != null) {
//				topBrickView.setIsOnTop(true, 6);
//			}	
		}
		
		override protected function updateLayout(event:Event = null):void {
			var bricks:Array = _pyramid.getBricksByRow(0);
			var visibleWidth:int = 0;
			for(var i:int = 0;i < bricks.length;i++) {
				if(bricks[i] != null) {
					var brick:Brick = Brick(bricks[i]);
					if(BrickView(brickViews[brick.id]).sprite.visible) {
						visibleWidth += 91;
					}
				}
			}
//			pyrContainer.x = int((760 - visibleWidth) / 2);
			checkForTopBrick();
			stateLayer.visible = false;
		}
		
		public function destroyView():void {
			for each(var bv:BrickView in brickViews){
				bv.destroy();
			}
			brickViews = new Array();
		}
		
		override public function update():void {
			timeline.removeChild(pyrContainer);
			pyrContainer = null;

			pyrContainer = new Sprite();
//			pyrContainer.y = 415;
			
			timeline.addChild(pyrContainer);
			
			pyrContainer.cacheAsBitmap = true;
			destroyView();
			onSetupDone();
		}
	}
}
